{% load static %}
{% load django_bootstrap5 %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}商城系统{% endblock %}</title>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/bootstrap-icons/1.10.0/font/bootstrap-icons.css">
    
    <!-- 基础样式 -->
    <link rel="stylesheet" href="{% static 'css/base.css' %}">
    <link rel="stylesheet" href="{% static 'css/hover_category_menu.css' %}">
    
    <!-- 额外样式 -->
    {% block extra_css %}{% endblock %}
    
    <!-- 用户菜单悬浮样式 -->
    <style>
        /* 用户菜单悬浮效果 */
        .user-menu-trigger {
            position: relative;
            z-index: 1000;
        }
        
        .user-menu-container {
            position: absolute;
            top: 100%;
            left: 50%;
            transform: translateX(-50%); /* 水平居中 */
            width: 200px;
            background-color: #fff;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            z-index: 1001;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
            border-radius: 4px;
            overflow: hidden;
            margin-top: 5px; /* 添加一点间距，避免干扰主链接点击 */
        }
        
        /* 使用JS控制，不再使用CSS hover */
        /*.user-menu-trigger:hover .user-menu-container {
            opacity: 1;
            visibility: visible;
        }*/
        
        .user-menu-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        
        .user-menu-item {
            border-bottom: 1px solid #f0f0f0;
        }
        
        .user-menu-item:last-child {
            border-bottom: none;
        }
        
        .user-menu-link {
            display: block;
            padding: 12px 15px;
            color: #333;
            text-decoration: none;
            transition: all 0.3s;
        }
        
        .user-menu-link:hover {
            background-color: #f8f9fa;
            color: #0d6efd;
        }
        
        .user-menu-divider {
            height: 1px;
            background-color: #e9ecef;
            margin: 0;
        }
        
        /* 响应式调整 */
        @media (max-width: 992px) {
            .user-menu-container {
                position: static;
                width: 100%;
                opacity: 1;
                visibility: visible;
                box-shadow: none;
                transform: none;
            }
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-light bg-white sticky-top">
        <div class="container">
            <a class="navbar-brand" href="{% url 'index' %}">
                <i class="bi bi-bag-heart-fill text-primary"></i> 商城系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
                    aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="{% url 'index' %}">首页</a>
                    </li>
                    <li class="nav-item hover-menu-trigger">
                        <a class="nav-link" href="#" id="navbarDropdown">
                            商品分类
                        </a>
                        {% if categories %}
                            {% include 'includes/hover_category_menu.html' %}
                        {% endif %}
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{% url 'new_products' %}">新品上架</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{% url 'on_sale_products' %}">热门促销</a>
                    </li>
                </ul>
                
                <!-- 搜索框 -->
                <form class="d-flex mx-auto" style="max-width: 400px;" action="{% url 'search' %}" method="get">
                    <div class="input-group">
                        <input class="form-control" type="search" name="q" placeholder="搜索商品..." aria-label="Search" value="{{ request.GET.q|default:'' }}">
                        <button class="btn btn-outline-primary" type="submit">
                            <i class="bi bi-search"></i>
                        </button>
                    </div>
                </form>
                
                <!-- 用户菜单 -->
                <div class="navbar-nav ms-auto">
                    {% if user.is_authenticated %}
                    <a class="nav-link" href="{% url 'view_cart' %}">
                        <i class="bi bi-cart3"></i> 购物车
                        <span id="cart-count" class="badge bg-danger">
                            {% with cart_count=user.cart_items.count %}
                            {% if cart_count > 0 %}{{ cart_count }}{% endif %}
                            {% endwith %}
                        </span>
                    </a>
                    {% else %}
                    <a class="nav-link" href="{% url 'login' %}?next={% url 'view_cart' %}">
                        <i class="bi bi-cart3"></i> 购物车
                    </a>
                    {% endif %}
                    
                    {% if user.is_authenticated %}
                    <div class="nav-item user-menu-trigger">
                        <a class="nav-link d-flex align-items-center" href="{% url 'profile' %}">
                            <i class="bi bi-person-circle"></i> <span class="ms-1">{{ user.username }}</span>
                        </a>
                        <div class="user-menu-container">
                            <ul class="user-menu-list">
                                <li class="user-menu-item">
                                    <a class="user-menu-link" href="{% url 'profile' %}">
                                        <i class="bi bi-person"></i> 个人中心
                                    </a>
                                </li>
                                <li class="user-menu-item">
                                    <a class="user-menu-link" href="{% url 'order_list' %}">
                                        <i class="bi bi-box-seam"></i> 我的订单
                                    </a>
                                </li>
                                <li class="user-menu-item">
                                    <div class="user-menu-divider"></div>
                                </li>
                                <li class="user-menu-item">
                                    <a class="user-menu-link" href="{% url 'logout' %}">
                                        <i class="bi bi-box-arrow-right"></i> 退出登录
                                    </a>
                                </li>
                            </ul>
                        </div>
                    </div>
                    {% else %}
                    <a class="nav-link" href="{% url 'login' %}"><i class="bi bi-box-arrow-in-right"></i> 登录</a>
                    <a class="nav-link" href="{% url 'register' %}"><i class="bi bi-person-plus"></i> 注册</a>
                    {% endif %}
                </div>
            </div>
        </div>
    </nav>
    
    <!-- 消息弹窗容器 -->
    <div id="toast-container" class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 1500;">
        {% if messages %}
            {% for message in messages %}
                <div class="toast toast-message align-items-center {% if message.tags == 'error' %}bg-danger{% elif message.tags == 'warning' %}bg-warning{% elif message.tags == 'success' %}bg-success{% else %}bg-info{% endif %} text-white border-0" role="alert" aria-live="assertive" aria-atomic="true">
                    <div class="d-flex">
                        <div class="toast-body">
                            <i class="bi {% if message.tags == 'error' %}bi-exclamation-triangle-fill{% elif message.tags == 'warning' %}bi-exclamation-circle-fill{% elif message.tags == 'success' %}bi-check-circle-fill{% else %}bi-info-circle-fill{% endif %} me-2"></i>
                            {{ message }}
                        </div>
                        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                    </div>
                </div>
            {% endfor %}
        {% endif %}
    </div>
    
    <!-- 主要内容 -->
    <main>
        {% block content %}{% endblock %}
    </main>
    
    <!-- 页脚 -->
    <footer class="bg-white py-4 mt-5">
        <div class="container">
            <div class="row">
                <div class="col-md-3 mb-4">
                    <h5>关于我们</h5>
                    <ul class="list-unstyled">
                        <li><a href="#" class="text-muted">公司简介</a></li>
                        <li><a href="#" class="text-muted">联系我们</a></li>
                        <li><a href="#" class="text-muted">招贤纳士</a></li>
                        <li><a href="#" class="text-muted">隐私政策</a></li>
                    </ul>
                </div>
                <div class="col-md-3 mb-4">
                    <h5>购物指南</h5>
                    <ul class="list-unstyled">
                        <li><a href="#" class="text-muted">购物流程</a></li>
                        <li><a href="#" class="text-muted">会员介绍</a></li>
                        <li><a href="#" class="text-muted">常见问题</a></li>
                        <li><a href="#" class="text-muted">联系客服</a></li>
                    </ul>
                </div>
                <div class="col-md-3 mb-4">
                    <h5>配送方式</h5>
                    <ul class="list-unstyled">
                        <li><a href="#" class="text-muted">上门自提</a></li>
                        <li><a href="#" class="text-muted">211限时达</a></li>
                        <li><a href="#" class="text-muted">配送服务查询</a></li>
                        <li><a href="#" class="text-muted">配送费收取标准</a></li>
                    </ul>
                </div>
                <div class="col-md-3 mb-4">
                    <h5>关注我们</h5>
                    <div class="d-flex">
                        <a href="#" class="text-muted me-3 fs-5"><i class="bi bi-wechat"></i></a>
                        <a href="#" class="text-muted me-3 fs-5"><i class="bi bi-sina-weibo"></i></a>
                        <a href="#" class="text-muted me-3 fs-5"><i class="bi bi-chat-fill"></i></a>
                        <a href="#" class="text-muted fs-5"><i class="bi bi-envelope-fill"></i></a>
                    </div>
                    <div class="mt-3">
                        <p class="mb-1">客服热线</p>
                        <h5 class="text-primary">400-123-4567</h5>
                    </div>
                </div>
            </div>
            <hr>
            <div class="text-center">
                <p class="mb-0 text-muted">&copy; 2025 商城系统 版权所有</p>
            </div>
        </div>
    </footer>
    
    <!-- Bootstrap 5 JS -->
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.3/js/bootstrap.bundle.min.js"></script>
    
    <!-- 基础脚本 -->
    <script src="{% static 'js/base.js' %}"></script>
    
    <!-- 消息提醒脚本 -->
    <script>
        // 页面加载完成后初始化消息提醒
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化所有Toast组件
            const toastElements = document.querySelectorAll('.toast');
            toastElements.forEach(function(toastEl) {
                // 创建Bootstrap的Toast实例
                const toast = new bootstrap.Toast(toastEl, {
                    autohide: true,
                    delay: 5000  // 5秒后自动隐藏
                });
                // 显示Toast
                toast.show();
            });
        });
        
        // 全局函数：显示自定义消息
        function showToast(message, type = 'info') {
            // 获取Toast容器
            const container = document.getElementById('toast-container');
            
            // 创建新的Toast元素
            const toastEl = document.createElement('div');
            toastEl.className = `toast toast-message align-items-center bg-${type} text-white border-0`;
            toastEl.setAttribute('role', 'alert');
            toastEl.setAttribute('aria-live', 'assertive');
            toastEl.setAttribute('aria-atomic', 'true');
            
            // 设置图标
            let icon = 'bi-info-circle-fill';
            if (type === 'success') icon = 'bi-check-circle-fill';
            else if (type === 'warning') icon = 'bi-exclamation-circle-fill';
            else if (type === 'danger') icon = 'bi-exclamation-triangle-fill';
            
            // 设置Toast内容
            toastEl.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">
                        <i class="bi ${icon} me-2"></i>
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            `;
            
            // 添加到容器
            container.appendChild(toastEl);
            
            // 创建Bootstrap Toast实例
            const toast = new bootstrap.Toast(toastEl, {
                autohide: true,
                delay: 5000  // 5秒后自动隐藏
            });
            
            // 显示Toast
            toast.show();
            
            // Toast隐藏后从DOM中删除
            toastEl.addEventListener('hidden.bs.toast', function() {
                container.removeChild(toastEl);
            });
        }
    </script>
    
    <!-- 懒加载通用脚本 -->
    <script>
        // 图片懒加载功能
        function initLazyLoad() {
            const lazyImages = document.querySelectorAll('img.lazy-load');
            
            if ('IntersectionObserver' in window) {
                const imageObserver = new IntersectionObserver((entries, observer) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            const image = entry.target;
                            if (image.dataset.src) {
                                image.src = image.dataset.src;
                                image.classList.add('loaded');
                                observer.unobserve(image);
                            }
                        }
                    });
                });
                
                lazyImages.forEach(image => {
                    imageObserver.observe(image);
                });
            } else {
                // 回退方案，简单延迟加载
                setTimeout(() => {
                    lazyImages.forEach(image => {
                        if (image.dataset.src) {
                            image.src = image.dataset.src;
                            image.classList.add('loaded');
                        }
                    });
                }, 200);
            }
        }
        
        // 延迟加载组件
        function initDeferredLoading() {
            const deferredElements = document.querySelectorAll('.deferred-load');
            
            if ('IntersectionObserver' in window) {
                const elementObserver = new IntersectionObserver((entries, observer) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            const element = entry.target;
                            if (element.dataset.src) {
                                element.src = element.dataset.src;
                            }
                            element.classList.add('loaded');
                            element.classList.remove('deferred-load');
                            observer.unobserve(element);
                            
                            // 如果有延迟执行的函数
                            if (element.dataset.onload) {
                                try {
                                    new Function(element.dataset.onload)();
                                } catch (e) {
                                    console.error('Error executing deferred function:', e);
                                }
                            }
                        }
                    });
                });
                
                deferredElements.forEach(element => {
                    elementObserver.observe(element);
                });
            } else {
                // 回退方案
                setTimeout(() => {
                    deferredElements.forEach(element => {
                        if (element.dataset.src) {
                            element.src = element.dataset.src;
                        }
                        element.classList.add('loaded');
                        element.classList.remove('deferred-load');
                        
                        // 如果有延迟执行的函数
                        if (element.dataset.onload) {
                            try {
                                new Function(element.dataset.onload)();
                            } catch (e) {
                                console.error('Error executing deferred function:', e);
                            }
                        }
                    });
                }, 300);
            }
        }
        
        // 防抖函数
        function debounce(func, wait) {
            let timeout;
            return function(...args) {
                const context = this;
                clearTimeout(timeout);
                timeout = setTimeout(() => func.apply(context, args), wait);
            };
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化懒加载
            initLazyLoad();
            
            // 初始化延迟加载
            initDeferredLoading();
            
            // 滚动时再次检查懒加载
            window.addEventListener('scroll', debounce(() => {
                initLazyLoad();
                initDeferredLoading();
            }, 200));
        });
    </script>
    
    <!-- 全局CSS -->
    <style>
        /* 懒加载图片样式 */
        img.lazy-load {
            opacity: 0;
            transition: opacity 0.3s;
        }
        
        img.lazy-load.loaded {
            opacity: 1;
        }
        
        /* 延迟加载元素样式 */
        .deferred-load {
            opacity: 0;
            transition: opacity 0.3s;
        }
        
        .deferred-load.loaded {
            opacity: 1;
        }
        
        /* 平滑滚动 */
        html {
            scroll-behavior: smooth;
        }
    </style>
    
    <!-- 保存当前URL作为referer -->
    <script>
        // 保存当前页面URL作为referer
        function saveCurrentUrlAsReferer() {
            // 不保存登录和注册页面
            if (!window.location.pathname.includes('login') && 
                !window.location.pathname.includes('register')) {
                localStorage.setItem('refererUrl', window.location.href);
            }
        }
        
        // 在页面加载时保存来源URL
        document.addEventListener('DOMContentLoaded', function() {
            saveCurrentUrlAsReferer();
            
            // 为所有登录和注册链接添加点击事件
            document.querySelectorAll('a[href*="login"], a[href*="register"]').forEach(function(link) {
                link.addEventListener('click', function() {
                    saveCurrentUrlAsReferer();
                });
            });
        });
    </script>
    
    <!-- 额外脚本 -->
    {% block extra_js %}{% endblock %}
</body>
</html>